import axios from 'axios'
import { Toast } from 'vant'
import store from '@/store'
import router from '@/router/index.js'
import { authorizationsPut } from '@/api/login.js'
// import router from '@/router/index.js'
// 设置请求基地址 固定写法
const _axios = axios.create({
  baseURL: process.env.VUE_APP_URL
})

// 请求拦截
_axios.interceptors.request.use(
  // 请求成功
  config => {
    // console.log(config)
    // 设置请求头 config.headers.xxx依据接口文档
    if (!config.noToken) {
      config.headers.Authorization = `Bearer ${store.state.login.token}`
    }
    return config
  },
  //   请求失败
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截
_axios.interceptors.response.use(
  // 响应成功
  res => res.data,
  //   响应失败
  async error => {
    console.log('error', [error])
    if (error.response.status === 401) {
      try {
        const restoken = await authorizationsPut()
        console.log('resrefhToken', restoken)

        store.commit('login/setToken', restoken.data.token)
        return _axios(error.config)
      } catch {
        if (
          !error.config.noError &&
          error.response.data &&
          error.response.data.message
        ) {
          Toast.fail(error.response.data.message)
        }
        store.commit('login/setToken', '')
        router.push('/login?redirect=' + router.currentRoute.fullPath)
      }
    } else {
      if (
        !error.config.noError &&
        error.response.data &&
        error.response.data.message
      ) {
        Toast.fail(error.response.data.message)
      }
    }

    return Promise.reject(error)
  }
)

export default _axios
